package simulator.processes;

import java.util.PriorityQueue;

/**
 * Trida planovace oddedena od prioritni fronty slouzici pro uchovavani a postupneho zpracovavani procesu. 
 *
 */
public class Scheduler extends PriorityQueue<Process> implements ProcessListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5199842979210044951L;

	private int startTime, time;
	
	/**
	 * Vrati hodnotu aktualiho casu v sekundach.
	 * @return Aktualni cas v sekundach.
	 */
	public int getTime() {
		return time;
	}

	private SchedulerListener listener = null;
	
	/**
	 * Cstor.
	 * @param listener Listener planovace.
	 * @param start_time Pocatecni cas planovace v sekundach.
	 */
	public Scheduler(SchedulerListener listener, int start_time) {
		super(8);
		this.listener = listener;
		
		this.startTime = start_time;
		time = start_time;
	}
	
	/**
	 * Uvede stav planovace do vychozich hodnot.
	 */
	public void reset() {
		this.clear();
		time = startTime;
	}
	
	@Override
	public boolean add(Process e) {
		e.setListener(this);
		e.setScheduler(this);
		return super.add(e);
	}
	
	/**
	 * Metoda pro zpracovani nasledujiciho procesu.
	 * @return Zpracovany proces.
	 */
	public Process processNextEvent() {
		Process proc = this.poll();
		if(proc != null) {
			time = proc.getWakeTime();
			proc.process();
		}
		return proc;
	}

	@Override
	public void onProcessProcessed(Process process) {
		if(listener != null)
			listener.onProcessProcessed(process);
	}

	@Override
	public void onProcessUpdated(Process process) {
		this.add(process);
		if(listener != null)
			listener.onProcessUpdated(process);
	}
	
}
